﻿from pycad.system import *

class upopen(object):
    '''upopen(obj: acdb.DBObject)
    提升acdb.DBObject对象的打开权限(上下文管理器)'''
    
    def __init__(self, obj):
        self._obj = obj
        self._isnotify = obj.IsNotifyEnabled
        self._isread = not obj.IsWriteEnabled
        if self._isnotify:
            self._obj.UpgradeFromNotify()
        elif self._isread:
            self._obj.UpgradeOpen()

    def __enter__(self):
        return self

    def __exit__(self, t, v, b):
        if b is None:
            if self._isnotify:
                self._obj.DowngradeToNotify()
            elif self._isread:
                self._obj.DowngradeOpen()

class cs(object):
    _ucm = acap.Application.UserConfigurationManager
    @classmethod
    def opencprofile(cls):
        return cs(cls._ucm.OpenCurrentProfile())
    @classmethod
    def openglobal(cls):
        return cs(cls._ucm.OpenGlobalSection())
    @classmethod
    def opendialog(cls, dialog):
        return cs(cls._ucm.OpenDialogSection(dialog))

    def __init__(self, csobj):
        self._cs = csobj
        self.sections = {}
    def __enter__(self):
        return self
    def __exit__(self, t, v, b):
        if b is None: self._close()
    def _close(self):
        for s in self.sections.values():
            s._close()
        self._cs.Close()
        self._cs.Dispose()
    def __getattr__(self, name):
        if self._cs.ContainsSubsection(name):
            if not self.sections.has_key(name):
                self.sections[name] = cs(self._cs.OpenSubsection(name))
            return self.sections[name]
    def __getitem__(self, key):
        if self._cs.Contains(key):
            return self._cs.ReadProperty(key, '')
    def __setitem__(self, key, value):
        if self._cs.Contains(key):
            self._cs.WriteProperty(key, value)

class _preperty(object):
    def __init__(self, cls):
        self._cls = cls
        self.__doc__ = cls.__doc__
        self.Overloads = cls.__new__.Overloads
    def __call__(self, *args):
        return self._cls(*self.__wrapargs(args))
    def __wrapargs(self, args):
        for a in args:
            if isinstance(a, tuple):
                if len(a) == 2:
                    yield acge.Point2d(*a)
                elif len(a) == 3:
                    yield acge.Point3d(*a)
            elif isinstance(a, list):
                if len(a) == 2:
                    yield acge.Vector2d(*a)
                elif len(a) == 3:
                    yield acge.Vector3d(*a)
            else:
                yield a

class dr(object):
    pass

import clr
for t in (eval('acdb.' + name) for name in dir(acdb)):
    if type(t) == type and issubclass(t, acdb.Entity):
        setattr(dr, t.__name__, _preperty(t))